package com.developerstation.barcode.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import my.utils.JacksonUtil;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.jackson.JsonParseException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.WebRequest;

import com.developerstation.barcode.config.Constant;
import com.developerstation.barcode.model.Admin;
import com.developerstation.barcode.model.Cka;
import com.developerstation.barcode.model.CkaTm;
import com.developerstation.barcode.service.AdminService;
import com.developerstation.barcode.service.CkaService;
import com.developerstation.barcode.service.TmService;


@Controller
@RequestMapping("/tm")
public class BarCodeController {
	
	private static final Log log = LogFactory.getLog(BarCodeController.class);
	
	private Map<String,Object> jsonMap = new HashMap<String,Object>();
	@Resource
	private TmService tmService;
	
	@Resource
	private AdminService adminService;
	
	@Resource
	private CkaService ckaService;
	
	
	@ExceptionHandler({Exception.class})
	@ResponseBody
	public String handleException(Exception e, WebRequest request){
		log.error("----------->>>handleException Error",e);
		jsonMap.clear();
		jsonMap.put("st", Constant.Base.FAIL);
		jsonMap.put("msg", "System Failed:" + e.getMessage());
		String resp = JacksonUtil.toJson(jsonMap);
		log.info("--------->>>resp is " + resp);
		return resp;
	}
	/**
	 * 登陆认证
	 * @param request
	 * @param response
	 * @return
	 */
	@SuppressWarnings("unused")
	@RequestMapping("/auth")
	@ResponseBody
	public Map<String,Object> login(Admin admin,HttpServletRequest request,HttpServletResponse response){
		log.info("--------->>>start login");
		jsonMap.clear();
		Admin ad = adminService.queryAdminByUserNamePasswordAndCKSoftPwd(admin);
		log.info("--------->>>Admin=" + ad);
		if(ad==null){
			jsonMap.put("st", Constant.Base.FAIL);
			jsonMap.put("msg", "验证信息错误");
		}else{
			jsonMap.put("st", Constant.Base.SUCCESS);
			jsonMap.put("admin", admin);
			jsonMap.put("msg", "验证成功");
		}
		return jsonMap;
	}
	
	/**
	 * 下载单据
	 * @param request
	y * @param response
	 * @return
	 */
	@RequestMapping("/dowloadCka")
	@ResponseBody
	public Map<String,Object> dowloadCka(String ck,HttpServletRequest request,HttpServletResponse response){
		log.info("--------->>>start dowloadCka");
		jsonMap.clear();
		if(ck == null){
			jsonMap.put("st", Constant.Base.FAIL);
			jsonMap.put("msg", "ck parameter is empty");
			return jsonMap;
		}
		List<Cka> list = ckaService.queryCkaListForLast30Days(ck);
		log.info("--------->>>cka list size="+ list.size() + " ," + list);
		jsonMap.put("st", Constant.Base.SUCCESS);
		jsonMap.put("list", list);
		jsonMap.put("msg", "成功");
		return jsonMap;
	}
	
	
	/**
	 * 上传条码数据
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException 
	 * @throws JsonParseException 
	 */
	@RequestMapping("/uploadTm")
	@ResponseBody
	public Map<String,Object> uploadTm(String jsonStr,HttpServletRequest request,HttpServletResponse response){
		//[{no:,ck:,operator:,type,tms:[{tm:,num:},{tm:,num:}]}]
		long _startTime = System.currentTimeMillis();
		log.info("--------->>>start uploadTm");
		jsonMap.clear();
		if(jsonStr == null ||"".endsWith(jsonStr)){
			jsonMap.put("st", Constant.Base.FAIL);
			jsonMap.put("msg", "jsonStr parameter is empty");
			return jsonMap;
		}
		List<CkaTm> listCkaList;
		try {
			listCkaList = assembleCkaTm(jsonStr);
//			tmService.insertList(listCkaList);
			tmService.insertUploadAndExecCallable(listCkaList);
			
			/*List<List> splitLists = ListUtils.splitList(listCkaList, 1000);
			for (List<CkaTm> list : splitLists) {
				log.info("---->>>" + list);
				tmService.insertForBatch(list);
				for(int i = 0; i < list.size(); i++){
					tmService.insertSelective(record);
				}
			}*/
			
			jsonMap.put("st", Constant.Base.SUCCESS);
			jsonMap.put("msg", "成功");
			
		} catch (Exception e) {
			log.error("--------->>>uploadTm Failed",e);
			jsonMap.put("st", Constant.Base.FAIL);
			jsonMap.put("msg", e.getMessage());
		}
		printProcessTime(_startTime,"uploadTm");
		
		return jsonMap;
	}
	public static List<CkaTm> assembleCkaTm(String jsonStr)
			throws JsonParseException, IOException {
		log.info("--------->>>jsonStr is = " + jsonStr);
		List<CkaTm> listCkaList = new ArrayList<CkaTm>();
		
		List<Map<String, Object>> list = JacksonUtil.parseToList(jsonStr);
		for (int i = 0; i < list.size(); i++) {
			Map<String, Object> map = list.get(i);  
			
			List<Map<String, Object>>  tmList =  (List<Map<String, Object>>) map.get("barcodeList");
			List<StringBuilder> tmSbList = new ArrayList<StringBuilder>();
			StringBuilder tmsbs = new StringBuilder();
			int tmCount = 0;
			for (Map<String, Object> map2 : tmList) {
				String tmStr = (String) map2.get("code");
				Integer num = (Integer) map2.get("count");
				for (int j = 0; j <num; j++) {
					tmsbs.append(tmStr);
					tmsbs.append("\r\n");
					tmCount++;
					if(tmCount==400){
						tmSbList.add(tmsbs);
						tmsbs = new StringBuilder();
						tmCount=0;
					}
				}
			}
			//不足400时
			tmSbList.add(tmsbs);
			for (StringBuilder stringBuilder : tmSbList) {
				String str = stringBuilder.toString();
				if(str==null||"".equals(str)){
					continue;
				}
				CkaTm record = new CkaTm();
				record.setCreateDate(new Date());
				record.setCk((String)map.get("storage"));
				record.setNo((String)map.get("no"));
				record.setType((String)map.get("type"));
				record.setOperator((String)map.get("operator"));
				record.setRepetition((Integer)map.get("repeatable"));
				record.setUpdateStatus((Integer)map.get("uploadStatus"));
				record.setTmUpload(str.trim());
				listCkaList.add(record);
			}
		}
		return listCkaList;
	}
	
	
	/**
	 * 得到单据审核状态
	 * @param noIds
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/checkApproval")
	@ResponseBody
	public Map<String,Object> checkApproval(String ck,String noList,HttpServletRequest request,HttpServletResponse response){
		log.info("--------->>>start checkApproval");
		jsonMap.clear();
		if(noList == null ||"".endsWith(noList) ||ck==null ||"".endsWith(ck)){
			jsonMap.put("st", Constant.Base.FAIL);
			jsonMap.put("msg", "noIds or ck parameter is empty");
			return jsonMap;
		}
		String[] noIdArray = noList.split(",");
		List<Cka> ckUnPostedIds = tmService.getUnPostedCk(ck,noIdArray);
		if(ckUnPostedIds == null){
			jsonMap.put("st", Constant.Base.SUCCESS);
			jsonMap.put("msg", "");
		}else{
			StringBuilder sb = new StringBuilder();
			for (int i = 0; i < ckUnPostedIds.size(); i++) {
				sb.append("'"+ckUnPostedIds.get(i).getNo()+"'");
				if(i!=(ckUnPostedIds.size()-1)){
					sb.append(",");
				}
			}
			jsonMap.put("st", Constant.Base.SUCCESS);
			jsonMap.put("msg", sb.toString());
		}
		
		return jsonMap;
	}
	public void printProcessTime(long _startTime,String ctx){
	    long _endTime = System.currentTimeMillis();
	    log.info("----------->>>Process Time:" + (_endTime-_startTime) + "ms " + ctx);
	}
}
